package com.smartpay.its.framework.remoting.rmi.client;

import java.io.IOException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.remoting.rmi.RmiProxyFactoryBean;

public class RemotingCallRmi {
	private static Properties prop;
	
	private static final Logger logger = LoggerFactory.getLogger(RemotingCallRmi.class);
	
	public static <V extends Object> Object getRmiService(String connectionUrl, Class<?> serviceInterface) {
		
		String url = connectionUrl + serviceInterface.getSimpleName();
		RmiProxyFactoryBean factory= new RmiProxyFactoryBean();
		factory.setServiceInterface(serviceInterface);
		factory.setServiceUrl(url);
		factory.afterPropertiesSet();
		Object stub = factory.getObject();
		return stub;
	}
	
	@SuppressWarnings("unchecked")
	public static <V extends Object> V getRmiServiceByModule(String module, Class<?> serviceInterface) {
		loadRemotingConfiguration();
		StringBuffer buf = new StringBuffer();
		buf.append("rmi://").append(prop.getProperty(module)).append('/');
		return (V) getRmiService(buf.toString(), serviceInterface);
	}
	
	
	private static void loadRemotingConfiguration() {
		if (null == prop) {
			prop = new Properties();
			try {
				prop.load(RemotingCallRmi.class.getClassLoader()
						.getResourceAsStream("properties/remoting.properties"));
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
	}
}
